import { useSimpleMemo, Void } from '@/components';
import { isEqualStrictDeep, pick } from '@/utils';
import * as PropTypes from 'prop-types';
import React, { forwardRef, useImperativeHandle } from 'react';

RefProp = forwardRef(RefProp);

const get = (p, k) =>
  k === true ? p : Array.isArray(k) ? k.map((kk) => get(p, kk)) : typeof k === 'function' ? k(p) : p[k] ?? null;

function RefProp(props, ref) {
  const { refKey, render, ...rest } = props;
  const ret = useSimpleMemo(get(pick(rest, ['children', 'component'])[1], refKey), isEqualStrictDeep);

  useImperativeHandle(ref, () => ret, [ret]);
  if (typeof render === 'function') return render(rest);

  const Comp = rest.component || Void;
  return <Comp {...rest} />;
}

RefProp.propTypes = {
  refKey: PropTypes.oneOfType([PropTypes.bool, PropTypes.string, PropTypes.arrayOf(PropTypes.string)]),
  component: PropTypes.elementType,
  children: PropTypes.node,
};

export default RefProp;
